package seeders

import (
	"goravel/app/models"

	"github.com/goravel/framework/facades"
)

type UserRoleSeeder struct {
}

// Signature The name and signature of the seeder.
func (s *UserRoleSeeder) Signature() string {
	return "UserRoleSeeder"
}

// Run executes the seeder logic.
func (s *UserRoleSeeder) Run() error {
	// 获取root001用户
	var user models.User
	if err := facades.Orm().Query().Where("username", "root001").First(&user); err != nil {
		facades.Log().Error("Failed to find root001 user: ", err)
		return err
	}

	// 获取超级管理员角色
	var adminRole models.Role
	if err := facades.Orm().Query().Where("role_name", "超级管理员").First(&adminRole); err != nil {
		facades.Log().Error("Failed to find admin role: ", err)
		return err
	}

	// 检查用户角色关联是否已存在
	var exists bool
	if err := facades.Orm().Query().Model(&models.UserRole{}).
		Where("user_id", user.ID).
		Where("role_id", adminRole.ID).
		Exists(&exists); err != nil {
		facades.Log().Error("Failed to check user role existence: ", err)
		return err
	}

	if !exists {
		userRole := models.UserRole{
			UserId: user.ID,
			RoleId: adminRole.ID,
		}

		if err := facades.Orm().Query().Create(&userRole); err != nil {
			facades.Log().Error("Failed to create user role: ", err)
			return err
		}
	}

	return nil
}
